import _ from "lodash";
import {useEffect, useState} from "react";
import {NavigateFunction, useSearchParams, useNavigate} from "react-router-dom";

interface UseNav {
    nav: NavigateFunction;
    params: any;
    handleNav: (...e: any) => any;
}

const useNav = (query = []): UseNav => {
    const nav = useNavigate();
    const [params, setParams] = useState({});
    const [searchParams] = useSearchParams();

    const handleNav = (url = "", params = {}, data = {}) => {
        let str = "";
        if (!_.isEmpty(params)) {
            str = _.map(params, (value, key) => `${key}=${value}`).join("&");
        }
        const goUrl = str ? `${url}?${str}` : url;
        nav(goUrl, data);
    };

    const handleGetPrams = () => {
        let info = {};
        _.forEach(query, key => {
            const val = searchParams.get(key) || "";
            info[key] = val;
        });
        setParams(info);
    };

    useEffect(() => {
        if (!_.isEmpty(query)) {
            handleGetPrams();
        }
    }, []);

    return {nav, params, handleNav};
};
export default useNav;
